package com.yh.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yh.entity.Zhanfeng;
import com.yh.exception.CodeException;
import com.yh.service.UserService;
import com.yh.service.impl.UserServiceImpl;

import cn.hutool.core.util.StrUtil;
@WebServlet("/login.let")
public class LoginServlet extends HttpServlet {

	private UserService userService = new UserServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String userName = req.getParameter("userName");
		String userPwd = req.getParameter("userPwd");
		String code = req.getParameter("code");
//		System.out.println("code="+code);
//		System.out.println("req.getSession().getAttribute(code)="+req.getSession().getAttribute("code"));
//		System.out.println(userName+"+"+userPwd);
		try {
			if(StrUtil.isEmpty(code)) {
				throw new CodeException(10,"验证码不能为空");
			}
			if(req.getSession().getAttribute("code")==null){
				throw new CodeException(11, "验证码已失效");
			}
			
			if(!code.equals(req.getSession().getAttribute("code"))){
				throw new CodeException(12, "验证码不匹配");
			}
			Zhanfeng user = userService.login(userName, userPwd);
			req.setAttribute("msg", "登录成功");
			req.setAttribute("href", "admin/user-list.let");
			req.getSession().setAttribute("user", user);
		} catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("error", e.getMessage());
		}
		
//		System.out.println(req);
		//跳转到视图
		req.getRequestDispatcher("/msg.jsp").forward(req, resp);//?
	}
	                                                                                                                                                                                                                                                  
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}
